use http_srv_multi::{handle_connection, ThreadPool, PORT};
use std::{net::TcpListener, thread};
fn main() -> std::io::Result<()>{
    let port = PORT();
    // ipv4
    // let listener = TcpListener::bind(format!("0.0.0.0:{}", port)).unwrap();
    // for stream in listener.incoming() {
    //     println!("Connection from {} established!", stream.as_ref().unwrap().peer_addr().unwrap());
    //     handle_connection(stream.unwrap());
    //     println!("Connection closed.");
    // }
    // ipv4/ipv6
    let ipv4_listener = TcpListener::bind(("0.0.0.0", port))?;
    let ipv6_listener = TcpListener::bind(("::1", port))?;
    // println!("{ipv6_listener:?}");
    // Handle incoming connection
    // for listener in vec![ipv4_listener, ipv6_listener] {
    //     let listener = listener;
    //     thread::spawn(move || {
    //         for stream in listener.incoming() {
    //             match stream {
    //                 Ok(stream) => {
    //                     thread::spawn(move || {
    //                         println!("Connection from {} established!", stream.peer_addr().unwrap());
    //                         handle_connection(stream);
    //                         println!("Connection closed.");
    //                     });
    //                 }
    //                 Err(e) => {
    //                     eprintln!("Error accepting stream: {}", e);
    //                 }
    //             }
    //         }
    //     });
    // }
    // // Keep the main thread running to keep the program alive
    // let _ = thread::park();
    for listener in vec![ipv4_listener, ipv6_listener] {
        thread::spawn(move || {
            // let listener = listener;
            // println!("-----{listener:?}");
            let pool = ThreadPool::new(3);
            for stream in listener.incoming() {
                // for stream in listener.incoming().take(2) { //优雅停机
                let stream = stream.unwrap();
                pool.execute(|| {
                    println!(
                        "Connection from {} established!",
                        stream.peer_addr().unwrap()
                    );
                    handle_connection(stream);
                    // println!("Connection closed.");
                });
            }
        });
    }
    // Keep the main thread running to keep the program alive
    let _ = thread::park();
    Ok(())
}
// IPV6本地访问方法：
// windows：可以使用http://0--1.ipv6-literal.net:9090/(微软自定义的ipv6本地地址访问)或http://[::1]:9090或[240e:804:510:a613:d8f0:c2f8:525c:284a]:9090本机的ipv6地址
// linux:http://[::1]:9090或[240e:804:510:a613:d8f0:c2f8:525c:284a]:9090本机的ipv6地址
//问题1：Address already in use
/*
/// 解决方法：
/// windows：
/// netstat -ano | findstr :<端口号> 来查找
/// taskkill /PID <进程ID> /F 杀掉进程
/// linux/macos:
/// lsof -i :<端口号>或netstat -tulnp |grep :<端口号>
/// kill -9 <进程ID> 杀掉进程
 */
